<template>
	<div class="single_image_upload">
		<template v-if="!!imageUrl">
			<el-image :src="imageUrlData" :preview-src-list="previewImage" fit="contain"></el-image>
		</template>
		<el-upload :accept="uploadAccept" :action="uploadImgUrl" v-bind="uploadConfig">
			<template v-if="!imageUrl">
				<el-button type="text" icon="el-icon-upload2">上传图片</el-button>
			</template>
			<template v-else>
				<el-button type="text">修改</el-button>
			</template>
		</el-upload>
		<template v-if="!!imageUrl">
			<el-button type="text" @click="handleDeleteImage()">删除</el-button>
		</template>
	</div>
</template>

<script>
import { mapActions } from 'vuex';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	mixins: [emitter],
	props: {
		value: String,
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		accept: {
			type: String,
			default: 'png,jpg,jpeg,webp'
		},
		//上传类型
		uploadType: {
			type: String,
			default: '1'
		}
	},
	data() {
		return {
			imageUrl: this.value,
			uploadImgUrl: `${process.env.VUE_APP_BASEURL}tbSysAttachment/upload`, // 上传的图片服务器地址
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				class: 'uploader',
				showFileList: false,
				onError: this.handleUploadError,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload,
				data: { showType: '1', type: this.uploadType },
				headers: { Authorization: this.$session.get('token') }
			},
			uploadParams: { showType: '1', type: this.uploadType }
		};
	},
	watch: {
		value(val) {
			this.imageUrl = val;
		},
		imageUrl(val) {
			this.$emit('input', val);
			this.dispatch('ElFormItem', 'el.form.change', [val]);
		}
	},
	computed: {
		uploadAccept() {
			let suffixArr = this.accept.split(',').map((item) => '.' + item);
			return suffixArr.join();
		},
		imageUrlData() {
			return window.staticPath + this.imageUrl;
		},
		previewImage() {
			return [this.imageUrlData];
		}
	},
	methods: {
		...mapActions(['getFileUrl']),
		//修改上传
		handleAmendUpload() {
			this.$refs['upload'].$el.querySelector('.uploadBtn').click();
		},

		// 删除图片
		handleDeleteImage() {
			this.imageUrl = '';
		},

		// 上传前loading加载
		handleBeforeUpload(file) {},

		// 文件个数超出
		handleExceed() {
			this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
		},

		// 上传成功回调
		handleUploadSuccess(res, file) {
			if (res.code === '0') {
				let datas = this.$detailData(res.data);
				this.imageUrl = datas.originalAddr;
			}
		},

		// 上传失败
		handleUploadError() {
			this.$message.error('上传图片失败，请重试');
		}
	}
};
</script>

<style lang="scss" scoped>
.single_image_upload::v-deep {
	display: flex;
	align-items: center;
	.el-image {
		display: block;
		width: 36px;
		height: 36px;
		flex-shrink: 0;
		background-color: rgba(0, 0, 0, 0.05);
	}
	.uploader {
		margin: 0 10px;
	}
	.el-button {
		padding: 10px 0;
		font-size: 14px;
	}
}
</style>
